package blog

import (
	"fmt"
	kroute "longblog/work/base/route"
	kbase "longblog/work/control/base"
	kdao "longblog/work/dao"
	kdaoblog "longblog/work/dao/blog"
	"math"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Home struct{}

func NewHome() *Home {
	return &Home{}
}
func (h *Home) Load() (route []kroute.RouteWrapStruct) {
	route = make([]kroute.RouteWrapStruct, 0)
	route = append(route, kbase.Wrap("GET", "/", h.index, kbase.MIDDLE_TYPE_NO_CHECK_LOGIN))
	route = append(route, kbase.Wrap("GET", "/home/:type_name", h.index, kbase.MIDDLE_TYPE_NO_CHECK_LOGIN))
	route = append(route, kbase.Wrap("GET", "/home/:type_name/:page", h.index, kbase.MIDDLE_TYPE_NO_CHECK_LOGIN))
	route = append(route, kbase.Wrap("GET", "/article/:id", h.article, kbase.MIDDLE_TYPE_NO_CHECK_LOGIN))
	return
}

//
func (h *Home) index(c *gin.Context) {
	type_name := kbase.GetParam(c, "type_name")
	page := kbase.GetParamInt64(c, "page")

	if page <= 0 {
		page = 1
	}
	nums := int64(2)
	offset := (page - 1) * nums

	var bloglist []map[string]interface{}
	var counts int64

	sql := "select a.id,a.title,a.updated_at,t.type_name from article as a join article_type as t on a.article_type_id=t.id where 1=1 "
	sqlCount := "select count(*) as int64_data from article as a join article_type as t on a.article_type_id=t.id where 1=1 "

	if len(type_name) > 0 && type_name != "all" {
		sql += " and t.type_name=? "
		sql += " limit ? offset ? "
		bloglist = kdao.Scans(nil, sql, type_name, nums, offset)

		sqlCount += " and t.type_name=? "
		counts = kdao.GetOneData(nil, sqlCount, type_name).Int64Data
	} else {
		sql += " limit ? offset ? "
		bloglist = kdao.Scans(nil, sql, nums, offset)

		counts = kdao.GetOneData(nil, sqlCount).Int64Data
	}

	//最大页数
	maxpage := int64(math.Ceil(float64(counts) / float64(nums)))

	g := make(gin.H)
	classifylist, _ := kdaoblog.ObjArticleType.GetAll(nil)

	g["title"] = "币小四;分享我的笔记"
	if len(type_name) > 0 && type_name != "all" {
		g["title"] = fmt.Sprintf("%s笔记;币小四", type_name)
	}
	g["bloglist"] = bloglist
	g["classifylist"] = classifylist
	g["prepage"] = page - 1
	g["page"] = page
	g["nextpage"] = page + 1
	g["maxpage"] = maxpage

	if type_name == "" {
		type_name = "all"
	}
	g["path_prefix"] = fmt.Sprintf("/home/%s/", type_name)
	c.HTML(http.StatusOK, "home/index.html", g)
}

//
func (h *Home) article(c *gin.Context) {

	id := kbase.GetParamInt64(c, "id")
	article, _ := kdaoblog.ObjArticle.GetById(nil, id)
	articleType, _ := kdaoblog.ObjArticleType.GetById(nil, article.ArticleTypeId)

	g := make(gin.H)
	classifylist, _ := kdaoblog.ObjArticleType.GetAll(nil)
	g["title"] = article.Title + ";币小四"
	g["article"] = article
	g["classifylist"] = classifylist
	g["type_name"] = articleType.TypeName
	c.HTML(http.StatusOK, "home/article.html", g)
}
